package com.ophiux.wechat.servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ophiux.wechat.db.MchAppModel;
import com.ophiux.wechat.db.Mch_App_Map;
import com.ophiux.wechat.utils.MD5Util;
import com.ophiux.wechat.utils.StringUtil;

/**
 * 说明：大坪医院授权地址<br>
 * <h1>创 建 人: hehailong<br></h1>
 * 创建日期: 2019年1月24日 下午2:06:26<br>
 * 需要的jar包:
 */
public class DPOauthServlet extends HttpServlet{
	private static final long serialVersionUID = 2422662486160118122L;
	private static Logger logger = LoggerFactory.getLogger(OauthServlet.class);
	private String REDIRECT_URL ="http://wechatpay.ophiux.com/OphiuxWeChatPayPlatformbuild/RedirectServlet";
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String token = request.getParameter("token");
		
		String appid="";
		String appsecret ="";
		MchAppModel mchApp = Mch_App_Map.getMchAppModelByMchId(token);
		if(!StringUtil.isEmpty(token)) {
			appid = mchApp.getAppid();
			appsecret = mchApp.getAppsecret();
		}else {
			appid = request.getParameter("appid");
			appsecret = request.getParameter("appsecret");
		}
		
		/**
		 * 回调至终端页面
		 */
		String client_back_url = request.getParameter("client_back_url");
		logger.info("回调至终端页面地址client_back_url="+client_back_url);
		client_back_url = URLEncoder.encode(client_back_url,"utf-8");

		String backUri = REDIRECT_URL+"?appid="+appid+"&appsecret="+appsecret+"&client_back_url="+client_back_url+"&token="+token;
		logger.info("REDIRECT_URL(回调地址)加密之前:"+backUri);
 	 	backUri = URLEncoder.encode(backUri,"utf-8");
		logger.info("REDIRECT_URL(回调地址)加密之后:"+backUri);
		//调用第三方地址
//		String url = "http://cqdpyy.hm.guahao.com/getCode?sign="+geiSign()+"&sourId=ophiux&RedirectUrl="+backUri;
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
				"appid=" + appid+
				"&redirect_uri=" +
				 backUri+
				"&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
		logger.info("接收到终端授权请求，授权链接为："+url);
		//重定向
		response.sendRedirect(url);
	}
	
	public static String geiSign() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
		String newDate = sdf.format(new Date());
		String signParam = "dsfsystem32567421@#!LS"+newDate;
		logger.info("调用大坪医院授权地址signParam="+signParam);
		String sign = MD5Util.MD5Encode(signParam, "utf-8");
		logger.info("调用大坪医院授权地址sign="+sign);
		return sign;
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
}
